/**
 * 
 */
package org.vidyakiran.app.server.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.vidyakiran.app.server.dao.VolunActivityDao;
import org.vidyakiran.app.server.dao.util.DatabaseUtils;
import org.vidyakiran.app.server.domain.entity.Organisation;
import org.vidyakiran.app.server.domain.entity.User;
import org.vidyakiran.app.server.domain.entity.VolunteeringActivity;

import com.google.appengine.api.datastore.Key;

/**
 * @author Harpreet
 *
 */
public class VolunActivityDaoJpaImpl implements VolunActivityDao {

	private EntityManager em;
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public VolunteeringActivity findActivityById(Key id) {
		em = DatabaseUtils.startTransaction(em);
		
		VolunteeringActivity activity = null;
		try {
			activity = em.find(VolunteeringActivity.class, id);
			//TODO Add child objects fetching as well, since the associated objects are Org and User, decision needs to 
			// made upto what level fetching is needed.
			
			em.getTransaction().commit();
		} finally {
			DatabaseUtils.cleanupTransaction(em);
		}
		return activity;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VolunteeringActivity saveNewActivityForOrg(Key orgId, VolunteeringActivity activity) {
		em = DatabaseUtils.startTransaction(em);
		
		try {
			Organisation org = em.find(Organisation.class, orgId);
			activity.setOrganisation(org);
			org.getActivities().add(activity);
			em.getTransaction().commit();
		} finally {
			DatabaseUtils.cleanupTransaction(em);
		}
		return activity;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VolunteeringActivity updateActivity(VolunteeringActivity activity) {
		em = DatabaseUtils.startTransaction(em);
		
		//Cleans and updates the userKeys with the users attached
		List<User> users = activity.getUsers();
		activity.getUserKeys().clear();
		for (User user : activity.getUsers()) {
			activity.getUserKeys().add(user.getId());
		}

		try {
			activity = em.merge(activity);
			em.getTransaction().commit();
		} finally {
			DatabaseUtils.cleanupTransaction(em);
		}
		
		//Put back the users collection before returning
		activity.setUsers(users);
		return activity;
	}

	/**
	 * {@inheritDoc}
	 * 
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<VolunteeringActivity> findAllActivitiesByName(String name) {
		em = DatabaseUtils.startTransaction(em);
		List<VolunteeringActivity> activities = null;
		
		try {
			Query query = em.createQuery(
					"select from " + VolunteeringActivity.class.getName() + " where interests == :name");
			query.setParameter("name", name);

			activities = (List<VolunteeringActivity>)query.getResultList();
			em.getTransaction().commit();
		} finally {
			DatabaseUtils.cleanupTransaction(em);
		}
		return activities;
	}

}
